package com.gxuwz.bignews.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.animation.AnimationUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.gxuwz.bignews.R;
import com.gxuwz.bignews.controller.RegisterController;
import com.gxuwz.bignews.model.util.NotificationUtil;

import java.util.Random;

public class RegisterFragment extends Fragment {
    private EditText etUsername, etPhone, etPassword, etConfirmPassword, etVerificationCode;
    private Button btnGetCode, btnRegister;
    private TextView tvToLogin;
    private RegisterController registerController;
    private FrameLayout notificationArea;
    private View notificationView;
    private String generatedCode;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register, container, false);

        registerController = new RegisterController(getContext());

        etUsername = view.findViewById(R.id.et_username);
        etPhone = view.findViewById(R.id.et_phone);
        etPassword = view.findViewById(R.id.et_password);
        etConfirmPassword = view.findViewById(R.id.et_confirm_password);
        etVerificationCode = view.findViewById(R.id.et_verification_code);
        btnGetCode = view.findViewById(R.id.btn_get_code);
        btnRegister = view.findViewById(R.id.btn_register);
        tvToLogin = view.findViewById(R.id.tv_to_login);
        notificationArea = view.findViewById(R.id.notification_area);

        btnGetCode.setOnClickListener(v -> getVerificationCode());
        btnRegister.setOnClickListener(v -> register());
        tvToLogin.setOnClickListener(v -> {
            if (getActivity() != null) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });

        return view;
    }

    private void getVerificationCode() {
        String phone = etPhone.getText().toString().trim();
        if (phone.isEmpty()) {
            Toast.makeText(getContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 生成随机6位验证码
        generatedCode = generateRandomCode();
        
        // 显示通知栏验证码
        if (getContext() != null) {
            NotificationUtil.showVerificationCodeNotification(getContext(), generatedCode);
            Toast.makeText(getContext(), "验证码已发送到通知栏", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 生成6位随机验证码
    private String generateRandomCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000); // 生成100000-999999之间的随机数
        return String.valueOf(code);
    }
    
    private void showTopNotification(String message) {
        if (getContext() == null) return;
        
        // 清除之前的通知（如果有）
        notificationArea.removeAllViews();
        
        // 加载通知视图
        LayoutInflater inflater = LayoutInflater.from(getContext());
        notificationView = inflater.inflate(R.layout.top_notification, notificationArea, false);
        
        // 设置通知消息
        TextView messageView = notificationView.findViewById(R.id.notification_message);
        messageView.setText(message);
        
        // 设置关闭按钮点击事件
        ImageView btnClose = notificationView.findViewById(R.id.btn_close);
        btnClose.setOnClickListener(v -> hideTopNotification());
        
        // 添加到通知区域
        notificationArea.addView(notificationView);
        
        // 应用动画
        notificationView.startAnimation(AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in));
        
        // 3秒后自动隐藏通知
        new Handler(Looper.getMainLooper()).postDelayed(
                this::hideTopNotification,
                3000
        );
    }
    
    private void hideTopNotification() {
        if (notificationView != null && notificationView.getParent() != null) {
            notificationView.startAnimation(AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_out));
            notificationArea.removeView(notificationView);
            notificationView = null;
        }
    }

    private void register() {
        String username = etUsername.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        String verificationCode = etVerificationCode.getText().toString().trim();

        if (username.isEmpty() || phone.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() || verificationCode.isEmpty()) {
            Toast.makeText(getContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!password.equals(confirmPassword)) {
            Toast.makeText(getContext(), "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        // 验证码检查
        if (generatedCode == null || !verificationCode.equals(generatedCode)) {
            Toast.makeText(getContext(), "验证码错误", Toast.LENGTH_SHORT).show();
            return;
        }

        if (registerController.isPhoneRegistered(phone)) {
            Toast.makeText(getContext(), "该手机号已注册", Toast.LENGTH_SHORT).show();
            return;
        }

        boolean result = registerController.registerUser(username, phone, password);
        if (result) {
            Toast.makeText(getContext(), "注册成功", Toast.LENGTH_SHORT).show();
            if (getActivity() != null) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        } else {
            Toast.makeText(getContext(), "注册失败", Toast.LENGTH_SHORT).show();
        }
    }
}